package org.com.lcuiot.handler;

import org.com.lcuiot.database.dto.Result;
import org.com.lcuiot.database.entity.SendCommand;
import org.com.lcuiot.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import static org.springframework.web.reactive.function.server.RouterFunctions.route;


/**
 * 设备信息处理器
 *
 * @author gaoge
 * @since 2022/10/27 15:29
 */
@RestController
public class DeviceHandler extends AbstractHandler {
    private final DeviceService deviceService;

    @Autowired
    public DeviceHandler(DeviceService deviceService) {
        this.deviceService = deviceService;
    }

    @Bean
    public RouterFunction<ServerResponse> deviceRouter() {
        return route()
                .POST("/send_command", this::sendCommand)
                .build();
    }

    /**
     * 给设备下达命令
     *
     * @param request 请求信息
     * @return Mono<ServerResponse>
     * @author gaoge
     */
    public Mono<ServerResponse> sendCommand(ServerRequest request) {
        return request.bodyToMono(SendCommand.class)
                .flatMap(s -> {
                    Result<Object> result = deviceService.sendCommand(s);
                    return resolveResult(result);
                });
    }


}
